//
//  CALoginController.m
//  cascade-realm
//
//  Created by QSC on 15/5/24.
//

#import "CALoginController.h"
#import "YYText.h"
#import "MyWebViewController.h"
#import "AppleIDLoginTool.h"
#import "CAMainTabbarController.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
@interface CALoginController ()
@property (nonatomic,strong)UIButton * loginBtn;
@property (nonatomic,strong)UIButton * appleBtn;
@property (nonatomic,strong)UIButton * checkBtn;
@property (nonatomic,strong)CAAlertView *alertView;
@end

@implementation CALoginController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = Hex(0xFCFFF6);
    
    [self setUpView];
    
    if (@available(iOS 14, *)) {

        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {

        }];

    }
  
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];

    UIImage *img = [Tool getBGImage:Hex(0XB3E600) and:Hex(0XD4E600) directionType:1 option:self.loginBtn.frame.size];
    self.loginBtn.backgroundColor = [UIColor redColor];
    [self.loginBtn setBackgroundImage:img forState:UIControlStateNormal];
    [self.loginBtn setBackgroundImage:img forState:UIControlStateHighlighted];
}

-(void)setUpView{
    
    UIImageView * bg = [[UIImageView alloc] initWithImage:Img(@"login_bg")];
    [self.view addSubview:bg];
    [bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        
    }];
    
    [self.view addSubview:self.loginBtn];
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(IsX?-280:-200);
        make.height.mas_equalTo(54);
        make.left.mas_equalTo(40);
    }];

    
    
    [self.view addSubview:self.appleBtn];
    
    [self.appleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.loginBtn.mas_bottom).offset(30);
        make.height.mas_equalTo(54);
        make.left.mas_equalTo(40);
    }];
    
    
    
    
    YYLabel *label = [YYLabel new];
    label.numberOfLines = 2;
    label.preferredMaxLayoutWidth = ScreenW;
    label.attributedText = [self settingAttr];;  //设置富文本

   
    
    [self.view addSubview:self.checkBtn];
    [self.checkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.appleBtn.mas_bottom).offset(42);
        make.left.equalTo(self.appleBtn).offset(29);
        make.width.height.mas_equalTo(20);
    }];
    
    
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.checkBtn);
        make.left.equalTo(self.checkBtn.mas_right).offset(5);
        
    }];
    
}


- (void)loginBtnClick{
    if (!_checkBtn.selected) {
        [self showAlertView];
        return;
    }
    

    
    UIDevice * device = [UIDevice currentDevice];
    
    NSDictionary *dic = @{
        @"oauthType":@"4",
        @"token":device.identifierForVendor.UUIDString
    };
    
    [Http PostLogWithPage:@"quicklogin"];
    
    [Http LoginPostWithURL:Oauth params:dic success:^(id  _Nonnull responseObject) {
        [CALoginController loginsuccess:responseObject];
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
    
    
}





//327073786jB
- (void)appleBtnClick{
  
    if (!_checkBtn.selected) {
        [self showAlertView];
        return;
    }
    [Http PostLogWithPage:@"applelogin"];
    [AppleIDLoginTool loginWithAppleId:^(NSString * _Nonnull userIdentifier, NSString * _Nonnull token) {
      
        NSDictionary *dic = @{
            @"oauthType":@"3",
            @"token":token
        };
        
        [Http LoginPostWithURL:Oauth params:dic  success:^(id  _Nonnull responseObject) {
            [CALoginController loginsuccess:responseObject];
         
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }];
}

- (void)checkBtnClick{
    _checkBtn.selected = !_checkBtn.isSelected;
}

- (void)cancelClick{
    [self.alertView removeFromSuperview];
}

- (void)agreeClick{
    _checkBtn.selected = YES;
    [self.alertView removeFromSuperview];
}

//登录成功
+ (void)loginsuccess:(id)responseObject{
    NSDictionary * data = responseObject[@"data"];
    if (data == nil) {
        //验证token之后登录
       
        
        [CAUserInfo refreshUserInfo:^{
            
        }];
        
      
    
    }else{
        //通过登录页面登录
        [[NSUserDefaults standardUserDefaults] setObject:data[@"token"] forKey:@"token"];
        
        NSMutableDictionary * userData = [NSMutableDictionary dictionaryWithDictionary:data[@"userInfo"]];
        userData[@"avatar"] = userData[@"avatarUrl"];
        
        CAUserInfo *userinfo = [CAUserInfo mj_objectWithKeyValues:userData];
    
        [[NSUserDefaults standardUserDefaults] setObject:userinfo.userId forKey:@"userId"];
        
        [CAUserInfo shared].userInfo = userinfo;
        
        
        [DBTool saveData:userData tag:userinfo.userId];
    }
  
    
    CYLBaseNavigationController * nav = [[CYLBaseNavigationController alloc] initWithRootViewController: [[CAMainTabbarController alloc] init]];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
    });
    
    [Http PostLogWithPage:@"loginsuccess"];
    
}

- (void)showAlertView{
    
    UIView * contentView = [UIView new];
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.layer.cornerRadius = 8;
    
    UIImageView * icon = [[UIImageView alloc] initWithImage:Img(@"icon")];
    icon.layer.cornerRadius = 12;
    icon.clipsToBounds = YES;
    [contentView addSubview:icon];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(contentView);
        make.width.height.mas_equalTo(64);
        make.top.mas_equalTo(32);
    }];
    
    
    UILabel * titlelabel = [UILabel LabelWithFont:BoldFont(14) color:Hex(0xC5E601) text:@"CascadeRealm"];
    [contentView addSubview:titlelabel];
    [titlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(contentView);
        make.top.equalTo(icon.mas_bottom).offset(8);
    }];
    
    YYLabel * privateLabel = [YYLabel new];
    privateLabel.numberOfLines = 2;
    privateLabel.attributedText = [self settingAttr];
    [contentView addSubview:privateLabel];

    [privateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(contentView);

        make.top.equalTo(titlelabel.mas_bottom).offset(16);

    }];

    UIButton * cancelBtn = [UIButton ButtonWithFont:Font(14) color:[[UIColor blackColor] colorWithAlphaComponent:0.3] text:@"Cancel"];
    cancelBtn.backgroundColor = Hex(0xF6F8FA);
    cancelBtn.layer.cornerRadius = 20;
    [contentView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView).offset(10);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(100);
        make.top.equalTo(privateLabel.mas_bottom).offset(28);
    }];
    
    
    UIButton * agreeBtn = [UIButton ButtonWithFont:Font(14) color:[UIColor whiteColor] text:@"Agree adn Continue"];
    agreeBtn.backgroundColor = [UIColor redColor];
    agreeBtn.layer.cornerRadius = 20;
    [contentView addSubview:agreeBtn];
   
    [agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.height.mas_equalTo(40);
        make.right.equalTo(contentView).offset(-10);
        make.width.mas_equalTo(160);
        make.top.equalTo(cancelBtn);
        make.bottom.equalTo(contentView).offset(-32);
    }];
    UIImage *img = [Tool getBGImage:Hex(0XB3E600) and:Hex(0XD4E600) directionType:1 option:CGSizeMake(40, 160)];
    [agreeBtn setBackgroundImage:img forState:UIControlStateNormal];
    [agreeBtn setBackgroundImage:img forState:UIControlStateHighlighted];
    agreeBtn.clipsToBounds = true;
    
    
    self.alertView = [CAAlertView ShowAlertWithContent:contentView];
    
    [cancelBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    [agreeBtn addTarget:self action:@selector(agreeClick) forControlEvents:UIControlEventTouchUpInside];
    
   
}

- (NSMutableAttributedString *)settingAttr{
    NSString * str = @"By using our App you agree with our \nTerm of Use and Privacy Policy.";
    NSMutableAttributedString *text  = [[NSMutableAttributedString alloc] initWithString: str];
    text.yy_lineSpacing = 5;
    text.yy_font = Font(14);
    text.yy_color = Hex(0x0C1011);
    
    NSRange range1 = [str rangeOfString:@"Term of Use"];
    NSRange range2 = [str rangeOfString:@"Privacy Policy."];
    WeakSelf
    [text yy_setAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range1];
    [text yy_setTextHighlightRange:range1 color:Hex(0xB3E600) backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        MyWebViewController *web = [MyWebViewController new];
        web.Fullurl = TermofUse;
        web.navTitle = @"Term of Use";
        [Http PostLogWithPage:@"terms"];
        [weakSelf.navigationController pushViewController:web animated:YES];
        if(weakSelf.alertView.superview != nil){
            [weakSelf.alertView removeFromSuperview];
        }
    }];
    
    [text yy_setAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range2];
    [text yy_setTextHighlightRange:range2 color:Hex(0xB3E600) backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        MyWebViewController *web = [MyWebViewController new];
        web.Fullurl = PrivacyPolicy;
        web.navTitle = @"Privacy Policy";
        [Http PostLogWithPage:@"privacy"];
        [weakSelf.navigationController pushViewController:web animated:YES];
        if(weakSelf.alertView.superview != nil){
            [weakSelf.alertView removeFromSuperview];
        }
    }];
    return text;
}



- (UIButton *)loginBtn{
    if (_loginBtn == nil) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setImage:Img(@"fast") forState:UIControlStateNormal];
        [_loginBtn setTitle:@"Fast Login" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginBtn.titleLabel.font = BoldFont(16);
        _loginBtn.layer.cornerRadius = 27;
        _loginBtn.clipsToBounds = YES;
        _loginBtn.layer.borderWidth = 1;
        _loginBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        [_loginBtn sizeToFit];
        [_loginBtn setButtonImageTitleStyle:ButtonImageTitleStyleLeft padding:20];
        [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return  _loginBtn;
}

- (UIButton *)appleBtn{
    if (_appleBtn == nil) {
        _appleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_appleBtn setImage:Img(@"apple_logo") forState:UIControlStateNormal];
        [_appleBtn setTitle:@"Sign in with Apple" forState:UIControlStateNormal];
        [_appleBtn setTitleColor:Hex(0x0A1117) forState:UIControlStateNormal];
        _appleBtn.titleLabel.font = BoldFont(16);
        _appleBtn.layer.cornerRadius = 27;
        _appleBtn.clipsToBounds = YES;
        _appleBtn.layer.borderWidth = 1;
        _appleBtn.layer.borderColor = Hex(0x657C47).CGColor;
        _appleBtn.backgroundColor = [UIColor whiteColor];
        [_appleBtn sizeToFit];
        [_appleBtn setButtonImageTitleStyle:ButtonImageTitleStyleLeft padding:20];
        [_appleBtn addTarget:self action:@selector(appleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return  _appleBtn;
}


- (UIButton *)checkBtn{
    if (_checkBtn == nil) {
        _checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_checkBtn setBackgroundImage:Img(@"selected1") forState:UIControlStateNormal];
        [_checkBtn setBackgroundImage:Img(@"selected2") forState:UIControlStateSelected];
        [_checkBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _checkBtn;
}
@end
